package com.wejoy.video.middle.station.data.util;

import org.apache.commons.lang3.StringEscapeUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具类
 */
public class StringUtils extends org.apache.commons.lang3.StringUtils {

    private static final String DASH = "-";

    /**
     * 缩略字符串（不区分中英文字符）
     *
     * @param str    目标字符串
     * @param length 截取长度
     * @return
     */
    public static String abbr(String str, int length) {
        if (str == null) {
            return "";
        }
        try {
            StringBuilder sb = new StringBuilder();
            int currentLength = 0;
            for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) {
                currentLength += String.valueOf(c).getBytes("GBK").length;
                if (currentLength <= length - 3) {
                    sb.append(c);
                } else {
                    sb.append("...");
                    break;
                }
            }
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取字符串中最后一个/后的字符
     *
     * @param str 输入字符串
     * @return 字符串中最后一个/之后的部分
     */
    public static String getLastSubstringAfterSlash(String str) {
        if (str != null && !str.isEmpty()) {
            int lastIndex = str.lastIndexOf('/');
            if (lastIndex != -1) {
                return str.substring(lastIndex + 1);
            }
        }
        return str; // 如果没有找到/，或输入为null或空，返回原字符串
    }

    /**
     * 替换掉HTML标签方法
     */
    public static String replaceHtml(String html) {
        if (isBlank(html)) {
            return "";
        }
        String regEx = "<.+?>";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(html);
        String s = m.replaceAll("");
        return s;
    }

    /**
     * 获取UUID
     *
     * @return uuid
     */
    public static String uuid() {
        return UUID.randomUUID().toString().replace(DASH, EMPTY);
    }

    /**
     * 批量发货时调用
     *
     * @return
     */
    public static synchronized String threadUUID() {
        return UUID.randomUUID().toString().replace(DASH, EMPTY);
    }

    /**
     * 获取N位随机数
     *
     * @param num
     * @return
     */
    public static String getRandomNumber(int num) {
        if (num <= 0) {
            throw new IllegalArgumentException();
        }
        double d = (Math.random() * 9 + 1) * (Math.pow(10, num - 1));
        return String.valueOf((int) d);
    }
}
